package impl

import (
	"context"

	"gitee.com/hexug/devcloud/mcenter/apps/service"
	"gitee.com/hexug/devcloud/mcenter/common/validate"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func (i *implServer) CreateService(ctx context.Context, in *service.CreateServiceRequest) (*service.Service, error) {
	if err := validate.V().Struct(in); err != nil {
		return nil, err
	}
	svc := service.NewService(in)
	if _, err := i.Col.InsertOne(ctx, svc); err != nil {
		return nil, err
	}
	return svc, nil
}
func (i *implServer) QueryService(ctx context.Context, in *service.QueryServiceRequest) (*service.ServiceSet, error) {
	if err := validate.V().Struct(in); err != nil {
		return nil, err
	}
	//防止过度获取
	if in.PageSize <= 0 || in.PageSize > 30 {
		in.PageSize = 5
	}
	if in.PageNumber <= 0 || in.PageNumber > 10 {
		in.PageNumber = 1
	}
	// fmt.Println(in)
	var filter bson.M
	//按创建时间倒排
	opt := options.Find().
		SetLimit(in.PageSize).
		SetSkip((in.PageNumber - 1) * in.PageSize).
		SetSort(bson.D{{Key: "created_at", Value: -1}}) //按创建时间倒序取出
	if in.Keyword != "" {
		filter = bson.M{"name": bson.M{"$regex": in.Keyword, "$options": "im"}}
	}
	cursor, err := i.Col.Find(ctx, filter, opt)
	if err != nil {
		return nil, err
	}
	d := service.NewServiceSet()
	if err := cursor.All(ctx, &d.Items); err != nil {
		return nil, err
	}
	count, err := i.Col.CountDocuments(ctx, filter)
	if err != nil {
		return nil, err
	}
	d.Total = count
	return d, nil
}
func (i *implServer) DetailService(ctx context.Context, in *service.DetailServiceRequest) (*service.Service, error) {
	if err := validate.V().Struct(in); err != nil {
		return nil, err
	}
	filter := bson.M{"_id": in.Value}
	if in.DetailType == service.DESCRIBE_BY_SERVICE_CREDENTAIL_ID {
		filter = bson.M{"credentail.client_id": in.Value}
	}
	res := i.Col.FindOne(ctx, filter)
	if res.Err() != nil {
		return nil, res.Err()
	}
	u := &service.Service{}
	if err := res.Decode(u); err != nil {
		return nil, err
	}
	return u, nil
}
